package com.hqyj.bigdata_project.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.hqyj.bigdata_project.entity.Users;
import com.hqyj.bigdata_project.json.R;
import com.hqyj.bigdata_project.service.UsersService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@RestController
@RequestMapping("users")
public class UsersController extends BaseController {

    @Resource
    private UsersService usersService;


    @GetMapping("auth")
    public R login(@RequestParam(value="identify",required = true) String identify, @RequestParam(value="password",required = true)String password, @RequestParam(value="token",required = true)String token,@RequestParam(value="code",required = true)String code) {
        //System.out.println("identify=" + identify + ",password=" + password);

        try {
            //首先检查验证码.
            if(!redisUtil.hasKey(token)){
                return R.fail("验证码验证失败！");
            }

            String sessionRandomCode = (String) redisUtil.get(token);
            if(!code.equalsIgnoreCase(sessionRandomCode)){
                return R.fail("验证码验证失败！");
            }

            Users loginSuccessUser = usersService.login(identify, password);
            if (loginSuccessUser != null) {
                //如果登录成功后，satoken生成令牌保存到redis中，并且返回给客户端。
                StpUtil.login(loginSuccessUser.getUid());
                return R.success("登录成功！", loginSuccessUser);
            } else {
                return R.fail("登录失败，请检查用户名或者密码是否正确！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }

    @PostMapping("/")
    public R reg(@RequestBody Users u) {
        try {
            if (usersService.register(u)) {
                return R.success("注册成功！");
            }
            return R.fail("注册失败！");

        } catch (Exception ex) {
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }

    @GetMapping("/isLogin")
    public R isLogin(){
        try{
           return R.success("判断登录状态成功！",StpUtil.isLogin());
        }catch (Exception ex){
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }

    @GetMapping("/logout")
    public R logout(){
        try{
            StpUtil.logout();
            return R.success("用户注销成功！");
        }catch (Exception ex){
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }
}
